import cv2
import numpy as np

# 读取图像
img = cv2.imread('./images/lena.png', cv2.IMREAD_GRAYSCALE)

# 步骤1：计算图像的直方图
hist = cv2.calcHist([img], [0], None, [256], [0, 256])

# 步骤2：使用Otsu算法选择初始阈值
ret, binary_otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
otsu_threshold = ret
print(f"Otsu初始阈值: {otsu_threshold}")

# 步骤3：计算两个类别的平均灰度值
foreground = img[img > otsu_threshold]
background = img[img <= otsu_threshold]


mean_foreground = np.mean(foreground)
mean_background = np.mean(background)

# 步骤4：计算新的阈值
new_threshold = (mean_foreground + mean_background) / 2
print(f"新的阈值: {new_threshold}")

# 使用新阈值进行二值化
_, binary = cv2.threshold(img, new_threshold, 255, cv2.THRESH_BINARY)

# 可视化结果
img_display = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
binary_display = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)

# 创建水平拼接的图像
h, w = img.shape
combined = np.zeros((h, w*2, 3), dtype=np.uint8)
combined[:, :w] = img_display
combined[:, w:] = binary_display

# 添加标题
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(combined, 'Original Image', (10, 30), font, 1, (255, 255, 255), 2)
cv2.putText(combined, 'Thresholded Image', (w+10, 30), font, 1, (255, 255, 255), 2)

# 显示结果
cv2.imshow('Thresholding Results', combined)
cv2.waitKey(0)
cv2.destroyAllWindows()